<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { Editor } from '@bytemd/vue-next'
import { useSettingsStore } from '../stores/settings'
import 'bytemd/dist/index.css'

// ByteMD插件
import gfm from '@bytemd/plugin-gfm'
import highlight from '@bytemd/plugin-highlight'
import math from '@bytemd/plugin-math'
import mermaid from '@bytemd/plugin-mermaid'
import gemoji from '@bytemd/plugin-gemoji'
import breaks from '@bytemd/plugin-breaks'
import frontmatter from '@bytemd/plugin-frontmatter'

// 导入插件样式
import 'highlight.js/styles/vs.css'
import 'katex/dist/katex.css'

// Props
const props = defineProps<{
  modelValue: string
  readOnly?: boolean
}>()

// Emits
const emit = defineEmits<{
  (e: 'update:modelValue', value: string): void
  (e: 'save', value: string): void
}>()

// 编辑器值
const content = ref(props.modelValue)

// 编辑模式：wysiwyg（所见即所得）, source（源码编辑）, split（双栏编辑）
const editorMode = ref('wysiwyg')

// 设置
const settingsStore = useSettingsStore()

// 插件
const plugins = [
  gfm(),
  highlight(),
  math(),
  mermaid(),
  gemoji(),
  breaks(),
  frontmatter()
]

// 编辑器配置
const editorConfig = computed(() => ({
  mode: editorMode.value as 'wysiwyg' | 'split' | 'tab',
  value: content.value,
  plugins: plugins,
  editorConfig: {
    lineNumbers: settingsStore.showLineNumbers,
    theme: settingsStore.isDarkMode ? 'dark' : 'light',
    styleActiveLine: true,
    indentWithTabs: true,
    tabSize: 2,
    lineWrapping: true,
    autoFocus: true,
    autofocus: true
  }
}))

// 处理内容变化
const handleChange = (value: string) => {
  content.value = value
  emit('update:modelValue', value)
  
  // 如果启用了自动保存，则在内容变化时自动保存
  if (settingsStore.autoSave) {
    emit('save', value)
  }
}

// 更改编辑模式
const changeEditorMode = (mode: string) => {
  editorMode.value = mode
  settingsStore.setEditorMode(mode)
}

// 保存内容
const saveContent = () => {
  emit('save', content.value)
}

// 监听v-model变化
watch(() => props.modelValue, (newValue) => {
  if (newValue !== content.value) {
    content.value = newValue
  }
})

// 监听主题变化
watch(() => settingsStore.isDarkMode, () => {
  // 强制更新编辑器以应用新主题
  const currentContent = content.value
  content.value = ''
  setTimeout(() => {
    content.value = currentContent
  }, 0)
})

// 初始化
onMounted(async () => {
  // 获取编辑器模式
  editorMode.value = await settingsStore.getEditorMode()
})
</script>

<template>
  <div class="markdown-editor">
    <div class="editor-toolbar">
      <div class="mode-selectors">
        <el-radio-group v-model="editorMode" size="small" @change="changeEditorMode">
          <el-radio-button label="wysiwyg">所见即所得</el-radio-button>
          <el-radio-button label="split">双栏模式</el-radio-button>
          <el-radio-button label="tab">源代码</el-radio-button>
        </el-radio-group>
      </div>
      
      <div class="actions">
        <el-button type="primary" size="small" @click="saveContent" :disabled="settingsStore.autoSave">
          {{ settingsStore.autoSave ? '自动保存中' : '保存' }}
        </el-button>
      </div>
    </div>
    
    <div class="editor-container">
      <Editor 
        v-bind="editorConfig"
        :readonly="readOnly"
        @change="handleChange"
      />
    </div>
  </div>
</template>

<style>
.markdown-editor {
  display: flex;
  flex-direction: column;
  height: 100%;
  width: 100%;
  overflow: hidden;
  background-color: var(--editor-bg-color, #fff);
}

.editor-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 16px;
  border-bottom: 1px solid var(--border-color);
  flex-shrink: 0;
  background-color: var(--editor-toolbar-bg, #f8f9fa);
}

.editor-container {
  flex: 1;
  overflow: hidden;
  position: relative;
  display: flex;
}

/* ByteMD样式调整 */
.bytemd {
  height: 100% !important;
  width: 100% !important;
  display: flex;
  flex-direction: column;
  flex: 1;
  font-size: var(--editor-font-size, 14px);
  line-height: var(--editor-line-height, 1.6);
  background-color: var(--editor-bg-color, #fff);
}

.bytemd-toolbar {
  flex-shrink: 0;
  background-color: var(--editor-toolbar-bg, #f8f9fa) !important;
  border-color: var(--border-color) !important;
}

.bytemd-toolbar .bytemd-toolbar-left {
  flex: 1;
  overflow: auto;
}

.bytemd-body {
  flex: 1 !important;
  overflow: hidden !important;
  display: flex !important;
  height: calc(100% - 48px) !important;
}

.bytemd-editor {
  flex: 1;
  overflow: hidden;
  height: 100% !important;
}

.bytemd-preview {
  background-color: var(--editor-preview-bg, #fff) !important;
  color: var(--text-color) !important;
  overflow-y: auto;
  padding: 0 16px;
  flex: 1;
  height: 100% !important;
}

.cm-editor {
  height: 100% !important;
}

.cm-scroller {
  overflow: auto !important;
}

/* 所见即所得模式下的样式 */
.bytemd[data-mode="wysiwyg"] .bytemd-body {
  height: 100% !important;
}

.bytemd[data-mode="wysiwyg"] .bytemd-preview {
  padding: 16px !important;
  width: 100% !important;
}

/* 样式调整以解决布局问题 */
.markdown-editor .CodeMirror {
  height: 100% !important;
}

/* 暗黑模式 */
.dark-mode .bytemd-toolbar {
  background-color: var(--editor-toolbar-bg, #2d2d2d) !important;
  color: var(--text-color) !important;
  border-color: var(--border-color, #333) !important;
}

.dark-mode .CodeMirror {
  background-color: var(--editor-bg-color, #1e1e1e) !important;
  color: var(--text-color) !important;
}

.dark-mode .bytemd-preview {
  background-color: var(--editor-preview-bg, #252526) !important;
  color: var(--text-color) !important;
}

.dark-mode .bytemd-toolbar .bytemd-toolbar-left > button.bytemd-toolbar-icon {
  color: var(--text-color-secondary) !important;
}

.dark-mode .bytemd-toolbar .bytemd-toolbar-right button.bytemd-toolbar-icon {
  color: var(--text-color-secondary) !important;
}

/* 选中样式 */
.bytemd-toolbar-icon.bytemd-tippy-active {
  color: var(--primary-color) !important;
}

.dark-mode .bytemd-toolbar-icon.bytemd-tippy-active {
  color: var(--primary-color) !important;
}

/* 编辑器预览样式调整 */
.bytemd-preview h1,
.bytemd-preview h2,
.bytemd-preview h3,
.bytemd-preview h4,
.bytemd-preview h5,
.bytemd-preview h6 {
  margin-top: 1.5em;
  margin-bottom: 0.5em;
  font-weight: 600;
  line-height: 1.25;
}

.bytemd-preview h1 {
  font-size: 2em;
  border-bottom: 1px solid var(--border-color);
  padding-bottom: 0.3em;
}

.bytemd-preview h2 {
  font-size: 1.5em;
  border-bottom: 1px solid var(--border-color);
  padding-bottom: 0.3em;
}

.bytemd-preview p,
.bytemd-preview blockquote,
.bytemd-preview ul,
.bytemd-preview ol,
.bytemd-preview dl,
.bytemd-preview table,
.bytemd-preview pre {
  margin-top: 0;
  margin-bottom: 1em;
}

.bytemd-preview img {
  max-width: 100%;
}

.bytemd-preview code {
  padding: 0.2em 0.4em;
  background-color: rgba(175, 184, 193, 0.2);
  border-radius: 6px;
}

.bytemd-preview pre code {
  padding: 0;
  background-color: transparent;
}

.bytemd-preview blockquote {
  padding: 0 1em;
  color: var(--text-color-secondary);
  border-left: 0.25em solid var(--border-color);
}

/* 修复预览区全高 */
.CodeMirror-scroll {
  height: 100% !important;
}

.bytemd-fullscreen {
  z-index: 1000;
}
</style> 